package com.idanchuang.support.etcache.local.caffeine;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.idanchuang.support.etcache.local.AbstractLocalCache;
import com.idanchuang.support.etcache.local.LocalCacheConfig;
import com.idanchuang.support.etcache.local.LocalKey;

/**
 *
 * 基于 Caffeine 实现的 LocalCache
 *
 * @author yjy
 * Created at 2021/12/21 11:57 上午
 */
public class CaffeineEtCache<K, V> extends AbstractLocalCache<K, V> {

    private final Cache<LocalKey<K>, V> cache;

    public CaffeineEtCache(LocalCacheConfig config) {
        super(config);
        this.cache = Caffeine.newBuilder()
                .maximumSize(config.getMaximumSize())
                .expireAfterWrite(config.getExpire(), config.getTimeUnit())
                .build();
    }

    @Override
    protected V doGet(LocalKey<K> localKey) {
        return cache.getIfPresent(localKey);
    }

    @Override
    protected void doSet(LocalKey<K> localKey, V value) {
        cache.put(localKey, value);
    }

    @Override
    protected void doRemove(LocalKey<K> localKey) {
        cache.invalidate(localKey);
    }

    @Override
    public void clear() {
        cache.invalidateAll();
    }

    @Override
    public int estimatedSize() {
        return (int) cache.estimatedSize();
    }
}
